package com.moji.service.impl;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.wxpay.sdk.WXPayUtil;
import com.google.gson.Gson;
import com.moji.common.config.WeChatConfig;
import com.moji.common.utils.CommonUtil;
import com.moji.common.utils.HttpRequestUtils;
import com.moji.common.utils.HttpUtils;
import com.moji.entity.MjOrder;
import com.moji.entity.MjOrderDetail;
import com.moji.entity.dto.MojiRefuseDto;
import com.moji.entity.vo.MijiMoYaoVo1;
import com.moji.service.MjOrderDetailService;
import com.moji.service.MjOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class WeChatService {
    @Autowired
    private WeChatConfig weChatConfig;
    @Resource
    private MjOrderService mjOrderService;
    @Autowired
    private MjOrderDetailService mjOrderDetailService;

    /**
     * 微信统一下单方法 生成用户扫码支付的二维码的URL
     * https://pay.weixin.qq.com/wiki/doc/api/native.php?chapter=9_1
     * 除付款码支付场景以外，商户系统先调用该接口在微信支付服务后台生成预支付交易单，返回正确的预支付交易会话标识后再按Native、JSAPI、APP等不同场景生成交易串调起支付。
     *
     * @return
     */
    public static String initiateRefund() throws Exception {

//		SortedMap<String,String> refundParams = new TreeMap<>();
//		refundParams.put("appid", "wxd3a921cb1ec69ba8");
//		refundParams.put("mch_id", "1526027941");
//		refundParams.put("nonce_str", CommonUtil.generateUUID());
//		refundParams.put("out_trade_no", "DD-240926-0013");
//		refundParams.put("out_refund_no", "DD-240926-0013");
//		refundParams.put("total_fee", String.valueOf("0.01"));
//		refundParams.put("refund_fee", String.valueOf("0.01"));
//		String sign = WXPayUtil.createSign(refundParams, "Mojiweather1513TOB15mojitianqiV2");
//		refundParams.put("sign", sign);
//		// 将参数转换为XML格式
//		String payXml = WXPayUtil.mapToXml(refundParams);
//
//		// 发送请求
//		URL url = new URL("https://api.mch.weixin.qq.com/secapi/pay/refund");
//		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
//		connection.setRequestMethod("POST");
//		connection.setDoOutput(true);
//		connection.setRequestProperty("Content-Type", "text/xml");
//
//		try (OutputStream os = connection.getOutputStream()) {
//			byte[] input = payXml.getBytes(StandardCharsets.UTF_8);
//			os.write(input, 0, input.length);
//		}
//		// 处理返回结果
//		// TODO: 解析返回XML并返回结果
//		String responseMessage = connection.getResponseMessage();
        return null;


//		// 设置API请求参数
//		Map<String, String> params = new HashMap<>();
//		params.put("appid", "wxd3a921cb1ec69ba8");
//		params.put("mch_id", "1526027941");
//		params.put("nonce_str", CommonUtil.generateUUID());
//		params.put("out_trade_no", "DD-240926-0013");
//		params.put("total_fee", "0.01");
//		params.put("refund_fee", "0.01");
//		params.put("out_refund_no", "DD-240926-0013");
//		params.put("notify_url", "http://47.93.153.16:8082//web/wechat/order/callback");
//		params.put("trade_type", "JSAPI");
//		params.put("openid", "YOUR_OPENID");
//
//		// 构建API请求URL
//		String url = "https://api.mch.weixin.qq.com/secapi/pay/refund";
//		HttpPost request = new HttpPost(url);
//		request.setHeader("Content-Type", "application/json");
//		request.setHeader("Accept", "application/json");
//		StringEntity entity = new StringEntity(params);
//		request.setEntity(entity);
//
//		// 发送API请求并获取响应结果
//		HttpClient client = HttpClientBuilder.create().build();
//		HttpResponse response = client.execute(request);
//		String responseBody = EntityUtils.toString(response.getEntity());
//		System.out.println(responseBody);


//		//int i = 1/0;   //模拟异常
//		//生成签名
//		SortedMap<String,String> params = new TreeMap<>();
////		params.put("appid",weChatConfig.getAppId());
//		params.put("appid","wxd3a921cb1ec69ba8");
////		params.put("mch_id", weChatConfig.getMchId());
//		params.put("mch_id", "1526027941");
//		params.put("nonce_str", CommonUtil.generateUUID());
//		params.put("out_trade_no","DD-240926-0013");
//		params.put("out_refund_no","DD-240926-0013");
////		params.put("total_fee",order.getPayAmount().multiply(new BigDecimal(100)).setScale( 0, BigDecimal.ROUND_DOWN).toString());
//		params.put("total_fee","0.01");
//		params.put("refund_fee","0.01");
//
//		params.put("notify_url","http://47.93.153.16:8082//web/wechat/order/callback");
//
//		//sign签名
//		String sign = WXPayUtil.createSign(params, "Mojiweather1513TOB15mojitianqiV2");
//		params.put("sign",sign);
//
//		//map转xml
//		String payXml = WXPayUtil.mapToXml(params);
//
////		log.info("------------#####################-------------payXml={}",payXml);
//
//		//统一下单
//		HttpsURLConnection conn = (HttpsURLConnection) new URL("https://api.mch.weixin.qq.com/secapi/pay/refund").openConnection();
//		conn.setRequestMethod("POST");
//		conn.setRequestProperty("Content-Type", "application/xml");
//		conn.setDoOutput(true);
//
//		OutputStream out = conn.getOutputStream();
//		out.write(payXml.getBytes(StandardCharsets.UTF_8));
//		out.flush();
//		out.close();
//
//		// 获取返回结果
//		BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream(), StandardCharsets.UTF_8));
//		StringBuilder response = new StringBuilder();
//		String line;
//		while ((line = in.readLine()) != null) {
//			response.append(line);
//		}
//		in.close();
//		conn.disconnect();
//
//// 解析返回的XML结果
//
//
//
//
////		String orderStr = HttpUtils.doPost(WeChatConfig.getUnifiedOrderUrl(),payXml,4000);
////		if(null == orderStr) {
////			return null;
////		}
////		log.info("------------#####################-------------orderStr={}",orderStr);
//
//		Map<String, String> unifiedOrderMap =  WXPayUtil.xmlToMap(response.toString());
//		System.out.println(unifiedOrderMap.toString());
//		if(unifiedOrderMap != null) {
////			log.info("------------#####################-------------code_url={}",unifiedOrderMap.get("code_url"));
//			return unifiedOrderMap.get("code_url");
//		}

//		return null;
    }

//    public static void main(String[] args) throws Exception {
//			}

    public Boolean refundOrder(String orderNo, String tranId) throws Exception {
        MjOrder mjOrder = mjOrderService.getOne(new LambdaQueryWrapper<MjOrder>()
                .eq(MjOrder::getOrderCode, orderNo));
        long begin = System.currentTimeMillis();
        //使用map封装微信支付需要的固定参数
        Map<String, String> m = new HashMap<>();
        //1、设置支付参数
        m.put("appid", "wxd3a921cb1ec69ba8");
        m.put("mch_id", "1526027941");
        m.put("nonce_str", CommonUtil.generateUUID());
        //微信支付订单号
        m.put("transaction_id", tranId);
        //商户退款单号
        m.put("out_refund_no", orderNo);
        //订单金额
        BigDecimal multiply = mjOrder.getOrderAmount().multiply(new BigDecimal("100")).setScale(0, RoundingMode.DOWN);
        m.put("total_fee", multiply.toString());
        //退款金额 即实际退款金额
        m.put("refund_fee", multiply.toString());
        //退款原因
        m.put("refund_desc", "不想要了");

        m.put("notify_url", "http://47.93.153.16:8082//web/wechat/order/callback");
        //生成签名
        m.put("sign", WXPayUtil.generateSignature(m, "Mojiweather1513TOB15mojitianqiV2"));

//		ORDER_REFUND_URL = "https://api.mch.weixin.qq.com/secapi/pay/refund";
        String content = HttpRequestUtils.refundRequest(WXPayUtil.mapToXml(m));


        //xml转为map接受结果
        Map<String, String> response = WXPayUtil.xmlToMap(content);
        long end = System.currentTimeMillis();
        String s = JSON.toJSONString(response);
        log.info("------------#####################-=" + s, s);
        if ("SUCCESS".equals(response.get("return_code")) && "SUCCESS".equals(response.get("result_code"))) {

            Map<String, String> param = new HashMap<>();
            param.put("refund_id", response.get("refund_id"));
            param.put("refund_fee", response.get("refund_fee"));
            //去除授权
            LambdaQueryWrapper<MjOrderDetail> mjOrderDetailLambdaQueryWrapper = new LambdaQueryWrapper<>();
            mjOrderDetailLambdaQueryWrapper.eq(MjOrderDetail::getOrderCode, orderNo);
            List<MjOrderDetail> list = mjOrderDetailService.list(mjOrderDetailLambdaQueryWrapper);
            if (list != null && list.size() > 0) {
                for (int i = 0; i < list.size(); i++) {
                    MojiRefuseDto mojiRefuseDto = new MojiRefuseDto();
                    if (list.get(i).getSpareInt2() != null) {
                        mojiRefuseDto.setAccessId(list.get(i).getSpareInt2());
                        Gson gson = new Gson();
                        // 将对象转换为JSON字符串
                        String jsonString = gson.toJson(mojiRefuseDto);
                        log.info("------------#####################-------------取消授权"+jsonString);
                        String s1 = HttpUtils.sendPutRequest("/tob-data-misc/eshop/access/deactivation", jsonString);
                        log.info("------------#####################-------------取消授权"+s1);
                        Gson gson1 = new Gson();
                        MijiMoYaoVo1 mijiMoYaoVo1 = gson1.fromJson(s1, MijiMoYaoVo1.class);
                        if (mijiMoYaoVo1 != null && mijiMoYaoVo1.getCode() == 200) {
                            //去消授权成功
                            MjOrderDetail mjOrderDetail = list.get(i);
                            mjOrderDetail.setSpareString2("");
                            mjOrderDetailService.updateById(mjOrderDetail);
                        }
                    }

                }
            }
            return true;
        }
        //为空代表退款失败
        return false;
    }


}
